﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace FreeSwitchEventViewer
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();          
        }
        int index = 0;
        List<string> _ListName = new List<string>();
        List<string> _ListText = new List<string>();

        private void btnLogInOut_Click(object sender, EventArgs e)
        {
            if (this.btnLogInOut.Text == "断开")
            {
                InboundSocket.Stop();
            }
            else if (this.btnLogInOut.Text == "连接")
            {
                if (int.TryParse(this.txtPort.Text, out var port))
                {
                    this.btnLogInOut.Text = "断开";
                    
                    this.Invoke(new Action(() => {
                        this.listBox1.Items.Clear();
                    }));
                    this._ListText.Clear();
                    this._ListName.Clear();
                    index = 0;
                    new Thread(() => {
                        InboundSocket.Start(this.txtIp.Text, port, this.txtPW.Text, EventRecvCallback, InboundSocketComplete);
                    }).Start();
                }
                else
                {
                    MessageBox.Show("端口号必须为数字");
                }      
            }           
        }

        void EventRecvCallback(string strName,string text)
        {
            this.Invoke(new Action(() => {
                this.listBox1.Items.Add($"{index}_{strName}");
            }));
            
            _ListText.Add($"{index}_{text}".Replace("\n","\r\n"));
            index++;
        }

        void InboundSocketComplete()
        {
            this.Invoke(new Action(() => {
                this.btnLogInOut.Text = "连接";
            }));
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

            this.Invoke(new Action(() => {
                if(_ListText.Count > this.listBox1.SelectedIndex)
                {
                    this.txtText.Text = _ListText[this.listBox1.SelectedIndex];
                }
                else
                {
                    this.txtText.Text = "index over flow";
                }
                
            }));
        }
    }
}
